/**
 * http://www.anddev.org/web_services_-_an_xml-rpc_client_for_android-t646.html
 */
package com.androdot;

import java.net.*;
import java.io.*;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import android.util.Log;
public class HttpRequest {
	/**
	 * HttpGet - doesn't read cookies
	 *
	 * @param sUrl
	 * @return
	 */
	public static HttpData get(String sUrl) {
		HttpData ret = new HttpData();
		String str;
		StringBuffer buff = new StringBuffer();
		try {
			URL url = new URL(sUrl);
			BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
			while ((str = in.readLine()) != null) {
				buff.append(str);
			}
			ret.content = buff.toString();
		} catch (Exception e) {
			Log.e("HttpRequest", e.toString());
		}
		return ret;
	}
	/**
	 * HTTP post request
	 *
	 * @param sUrl
	 * @param ht
	 * @return
	 * @throws Exception
	 */
	public static HttpData post(String sUrl, Hashtable<String, String> ht) throws Exception {
		StringBuffer data = new StringBuffer();
		Enumeration<String> keys = ht.keys();
		while (keys.hasMoreElements()) {
			data.append(URLEncoder.encode(keys.nextElement(), "UTF-8"));
			data.append("=");
			data.append(URLEncoder.encode(ht.get(keys.nextElement()), "UTF-8"));
			data.append("&");
		}
		return HttpRequest.post(sUrl, data.toString());
	}
	/**
	 * HTTP post request
	 *
	 * @param sUrl
	 * @param data
	 * @return
	 */
	public static HttpData post(String sUrl, String data) {
		StringBuffer ret = new StringBuffer();
		HttpData dat = new HttpData();
		try {
			// Send data
			URL url = new URL(sUrl);
			URLConnection conn = url.openConnection();
			conn.setDoOutput(true);
			OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
			wr.write(data);
			wr.flush();
			// Get the response
			Map<String, List<String>> headers = conn.getHeaderFields();
			Set<Entry<String, List<String>>> hKeys = headers.entrySet();
			for (Iterator<Entry<String, List<String>>> i = hKeys.iterator(); i.hasNext();) {
				Entry<String, List<String>> m = i.next();
				Log.w("HEADER_KEY", m.getKey() + "");
				dat.headers.put(m.getKey(), m.getValue().toString());
				if (m.getKey().equals("set-cookie"))
					dat.cookies.put(m.getKey(), m.getValue().toString());
			}
			BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String line;
			while ((line = rd.readLine()) != null) {
				ret.append(line);
			}
			wr.close();
			rd.close();
		} catch (Exception e) {
			Log.e("ERROR", "ERROR IN CODE:"+e.toString());
		}
		dat.content = ret.toString();
		return dat;
	}
}